package com.moli.iov.task.remoting.op.reponse;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.moli.iov.rest.RestResponse;
import com.moli.iov.task.constants.Constants;
import com.moli.iov.task.model.dto.VehicleBaseDto;
import com.moli.iov.util.HttpUtil;
import com.moli.iov.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * <p>
 *
 * </p>
 *
 * @Auther: zql
 * @Date: 2019/1/10 16:42
 */
@Slf4j
@Component
public class VehicleBaseNotifyResponseHandler {

    @Autowired
    private TokenResponseHandler tokenRequestHandler;

    @Value("${op_notify_tbox_url}")
    private String opNotifyTboxUrl;

    @Value("${op_channel_val}")
    private String opChannelVal;

    /**
     * 通知OP 安装Tbox
     * @param vehicleBaseDto
     * @return
     */
    public RestResponse notifyOp(VehicleBaseDto vehicleBaseDto) throws IOException {
        String token = tokenRequestHandler.getToken();
        return this.notifyOpReal(vehicleBaseDto, token);
    }

    /**
     * 通知OP 安装Tbox
     * @param vehicleBaseDto
     * @return
     */
    public RestResponse notifyOpReal(VehicleBaseDto vehicleBaseDto, String token){
        Map<String, Object> params = Maps.newHashMap();

        params.put("vin", vehicleBaseDto.getVin());
        params.put("iccid", vehicleBaseDto.getIccid());
        params.put("registerTime", vehicleBaseDto.getRegisterTime());

        Map<String, String> headers = Maps.newHashMap();
        headers.put("token", token);
        headers.put("channel", opChannelVal);
        String result = "";
        try{
            result = HttpUtil.postJson(opNotifyTboxUrl, JSONObject.toJSONString(params), headers);
        }catch(Exception e){
            log.error("通知OP 安装Tbox 调用OP服务异常", e);
            return RestResponse.failure("调用OP服务异常");
        }


        if(StringUtil.isBlank(result)){
            log.error("通知OP 安装Tbox 失败， OP返回空");
            return RestResponse.failure("知OP 安装Tbox 失败， OP返回空");
        }

        JSONObject jsonObject = JSONObject.parseObject(result);

        if(Constants.OP_SUCCESS != jsonObject.getInteger("code")){
            log.error("通知OP 安装Tbox失败，OP返回状态非200 token:{} 出参：{}", token, jsonObject);
            return RestResponse.failure(jsonObject.getString("message"));
        }
        log.info("通知OP 安装Tbox 成功  入参：{}  headers:{} OP返回数据:{}", params, headers, result);
        return RestResponse.success();
    }
}
